package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.annotation.LoginUser;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.Result;
import io.renren.dao.SmallCanteenPurchaseDao;
import io.renren.dao.SmallCanteenPurchasemxDao;
import io.renren.dto.*;
import io.renren.entity.SmallCanteenPurchaseEntity;
import io.renren.entity.UserEntity;
import io.renren.service.*;
import io.renren.utils.StringsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小食堂采购表
 *
 * @author 翟文闯 619556390@QQ.com
 * @since 1.0.0 2019-11-22
 */
@Service
public class SmallCanteenPurchaseServiceImpl extends CrudServiceImpl<SmallCanteenPurchaseDao, SmallCanteenPurchaseEntity, SmallCanteenPurchaseDTO> implements SmallCanteenPurchaseService {
    @Autowired
    private SmallCanteenPurchaseService smallCanteenPurchaseService;
    @Autowired
    private SmallCanteenPurchasemxService smallCanteenPurchasemxService;
    @Autowired
    private SmallCanteenPurchaseDao smallCanteenPurchaseDao;
    @Autowired
    private SmallCanteenPurchasemxDao smallCanteenPurchasemxDao;
    @Autowired
    private FinanceService financeService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private TemporaryOrderService temporaryOrderService;
    @Autowired
    private TemporaryOrdermxService temporaryOrdermxService;
    @Override
    public QueryWrapper<SmallCanteenPurchaseEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<SmallCanteenPurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.orderByDesc("create_date");
        return wrapper;
    }

    @Override
    public PageData<SmallCanteenPurchaseDTO> pageAdmin(Map<String, Object> params) {
        String canteenid = (String)params.get("canteenId");
        QueryWrapper<SmallCanteenPurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status", 1).orderByDesc("create_date");
        wrapper.eq(StringUtils.isNotBlank(canteenid),"canteen_id", Long.parseLong(canteenid));
        IPage<SmallCanteenPurchaseEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        return getPageData(page, SmallCanteenPurchaseDTO.class);
    }

    @Override
    public PageData<SmallCanteenPurchaseDTO> pagesTorehouseClerk(Map<String, Object> params, @LoginUser UserEntity entity) {
        QueryWrapper<SmallCanteenPurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.ge("status", 3);
        wrapper.eq("canteen_id",entity.getDeptId());
        wrapper.orderByDesc("create_date");
        IPage<SmallCanteenPurchaseEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper
        );
        PageData<SmallCanteenPurchaseDTO> pageData = getPageData(page, SmallCanteenPurchaseDTO.class);
        return pageData ;
    }

    @Override
    public Map selecSupplierSmallOrder(Long supplierId) {
        List<SmallCanteenPurchaseDTO> list = smallCanteenPurchaseDao.selecSupplierSmallOrder(supplierId);
        ArrayList<SmallCanteenPurchaseDTO> purchaseList = new ArrayList<>();
        for (SmallCanteenPurchaseDTO  smallCanteen:list) {
            List<SmallCanteenPurchasemxDTO> smallCanteenList = smallCanteenPurchasemxService.seletGysFood1(smallCanteen.getSmallCanteenPurchaseId(), supplierId);
            if(smallCanteenList.size()>0){
                SmallCanteenPurchasemxDTO smallmxDTO = smallCanteenList.get(0);
                smallCanteen.setSubStatus(smallmxDTO.getSubStatus());
                String deptName = sysDeptService.getDeptName(smallCanteen.getCanteenId()).getName();
                String str = StringsUtils.getCanteenName(deptName) + "食堂申请清单";
                smallCanteen.setChedRemark(str);
                purchaseList.add(smallCanteen);
            }
        }
        int pending =0;//计算未处理订单的数量
        for (SmallCanteenPurchaseDTO purchaseDTO: purchaseList) {
            if(0 == purchaseDTO.getSubStatus()){
                pending =pending+1;
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("pending",pending);
        map.put("list",purchaseList);
        return map;
    }

    @Override
    public PageData<SmallCanteenPurchaseDTO> getOrder(Map<String, Object> params, UserEntity entity) {
        QueryWrapper<SmallCanteenPurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq( "ched_id", entity.getId()).orderByDesc("create_date");
        IPage<SmallCanteenPurchaseEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                wrapper);
        PageData<SmallCanteenPurchaseDTO> pageData = getPageData(page, SmallCanteenPurchaseDTO.class);
        return pageData;
    }

    @Override
    public SmallCanteenPurchaseDTO get(long id) {
        SmallCanteenPurchaseEntity smallCanteenPurchaseEntity = baseDao.selectById(id);
        return ConvertUtils.sourceToTarget(smallCanteenPurchaseEntity, SmallCanteenPurchaseDTO.class);
    }

    @Transactional
    public void saveAuxiliaryOrder(JSONObject params,UserEntity entity) {
        System.out.println(params);
            SmallCanteenPurchaseDTO smallCanteenDTO = new SmallCanteenPurchaseDTO();
            smallCanteenDTO.setChedId(entity.getId());
            smallCanteenDTO.setChedRemark((String) params.get("chedRemark"));
            smallCanteenDTO.setBoxId((String) params.get("boxId"));
            String mealTime = (String) params.get("mealTime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                Date date = sdf.parse(mealTime);
                smallCanteenDTO.setMealTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            smallCanteenDTO.setCreateDate(new Date());
            //获取当前部门信息
            smallCanteenDTO.setCanteenId(entity.getDeptId());
            smallCanteenPurchaseService.save(smallCanteenDTO);
            Long smallCanteenPurchaseId = smallCanteenDTO.getSmallCanteenPurchaseId();
            ArrayList<LinkedHashMap> list = (ArrayList) params.get("list");
            for (int i = 0; i < list.size(); i++) {
                LinkedHashMap<String, Object> list1 = list.get(i);
                String supplierId = (String) list1.get("supplierId");
                if (null != supplierId) {
                    ArrayList<LinkedHashMap> foods = (ArrayList) list1.get("foods");
                    for (int j = 0; j < foods.size(); j++) {
                        SmallCanteenPurchasemxDTO smallchasemxDTO = new SmallCanteenPurchasemxDTO();
                        String foodId = (String) foods.get(j).get("foodId");
                        smallchasemxDTO.setFoodId(Long.parseLong(foodId));
                        smallchasemxDTO.setSupplierId(Long.parseLong(supplierId));
                        Float num = 1F;
                        String purchaseNum = String.valueOf(foods.get(j).get("purchaseNum"));
                        if (null != purchaseNum) {
                            num = Float.parseFloat(purchaseNum);
                        }
                        smallchasemxDTO.setPurchaseNum(num);
                        smallchasemxDTO.setSmallCanteenPurchaseId(smallCanteenPurchaseId);
                        smallCanteenPurchasemxService.save(smallchasemxDTO);
                    }
                }
        }
        TemporaryOrderDTO temOrder = temporaryOrderService.getTemOrder(2, entity.getId(), entity.getDeptId());
        temporaryOrderService.deleteOrder(3,entity.getDeptId());
        temporaryOrdermxService.deleteOrder(temOrder.getTemporaryId());
    }

    @Override
    public List<SmallCanteenPurchaseDTO> home(Map<String, Object> params) {
        QueryWrapper<SmallCanteenPurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date").last("limit 3");
        List<SmallCanteenPurchaseEntity> list = baseDao.selectList(queryWrapper);

        return ConvertUtils.sourceToTarget(list, SmallCanteenPurchaseDTO.class);
    }

    @Override
    public Result updateExamine(SmallCanteenPurchaseDTO dto, UserEntity userEntity) {
        //如果到货数量或者照片没有传抛出异常
        if (3 == dto.getStatus()) {
            //根据订单号查询详情 并遍历，判断空
            List<SmallCanteenPurchasemxDTO> smallCanteenPurchasemxDTOList = smallCanteenPurchasemxService.selectGyss2(dto.getSmallCanteenPurchaseId());
            for (SmallCanteenPurchasemxDTO smallCanteenPurchasemxDTO : smallCanteenPurchasemxDTOList) {
                if(1== smallCanteenPurchasemxDTO.getSubStatus()){
                    List<SmallCanteenPurchasemxDTO> dtoList = smallCanteenPurchasemxService.selectFoods(smallCanteenPurchasemxDTO.getSmallCanteenPurchaseId(), smallCanteenPurchasemxDTO.getSupplierId());
                    for (SmallCanteenPurchasemxDTO purchasemxDTO:dtoList) {
                        if(0!=purchasemxDTO.getArrivalNum()) {
                            if (null == purchasemxDTO.getArrivalNum() || StringUtils.isBlank(purchasemxDTO.getEntityPhoto())) {
                                Result result = new Result();
                                return result;
                            }
                        }
                    }
                }
            }
        }
        if (dto.getStatus() == 4) {
            dto.setStatus(5);
            dto.setConfirmDatetime(new Date());

            saveFinance(dto.getSmallCanteenPurchaseId(),userEntity.getDeptId()); //主厨审核通过状态5 生成订单
            dto.setChedId(userEntity.getId());
        }else if (dto.getStatus() == 3) {
            dto.setStatus(4);
            dto.setReceivingGoodsTime(new Date());
            dto.setStorehouseClerkId(userEntity.getId());
        }else if (dto.getStatus() == 1) {
            dto.setStatus(2);
            dto.setAuditTime(new Date());
            dto.setCanteenAdminId(userEntity.getId());
        }
        update(dto);
        return new Result();
    }

    @Override
    public Result UpdateSupplierOrder(SmallCanteenPurchaseDTO dto, UserEntity userEntity) {
        List<SmallCanteenPurchasemxDTO> dtoList = smallCanteenPurchasemxDao.seletGysFood(dto.getSmallCanteenPurchaseId(), userEntity.getId());
        for (SmallCanteenPurchasemxDTO purchasemxDTO:dtoList) {
            smallCanteenPurchasemxService.updateOrder1(purchasemxDTO.getSmallCanteenPurchasemxId(),1);

        }
        SmallCanteenPurchaseDTO smallCanteenPurchaseDTO = smallCanteenPurchaseService.get(dto.getSmallCanteenPurchaseId());
        if(2==smallCanteenPurchaseDTO.getStatus()){
            dto.setStatus(3);
            dto.setQuotationTime(new Date());
            dto.setSupplierId(userEntity.getId());
            update(dto);
        }
        return new Result();
    }

    /**
     * 生成财务订单
     *
     * @param order
     */
    void saveFinance(Long order,Long id) {
        List<SmallCanteenPurchasemxDTO> smallCanteenList = smallCanteenPurchasemxDao.gys1(order);
        for (SmallCanteenPurchasemxDTO smallCanteenmx : smallCanteenList) {
            Float total = 0F;
            List<SmallCanteenPurchasemxDTO> list = smallCanteenPurchasemxService.selectFoods(smallCanteenmx.getSmallCanteenPurchaseId(), smallCanteenmx.getSupplierId());
            for (SmallCanteenPurchasemxDTO smallCanteenmxDTO : list) {
                //单价*数量
                Float mult = StringsUtils.mult(smallCanteenmxDTO.getArrivalNum(), smallCanteenmxDTO.getUnitPrice());
                total = total + mult;
            }
            FinanceDTO financeDTO = new FinanceDTO();
            financeDTO.setAmountPayable(total);
            financeDTO.setSupplierId(smallCanteenmx.getSupplierId());
            financeDTO.setOrderid(smallCanteenmx.getSmallCanteenPurchaseId());
            financeDTO.setFinanceId(smallCanteenmx.getFinanceId());
            financeDTO.setSupplierId(smallCanteenmx.getSupplierId());
            financeDTO.setCreateDate(smallCanteenmx.getCreateDate());
            financeDTO.setCanteenId(id+"");
            financeDTO.setType("3");
            financeService.save(financeDTO);
        }
    }

    /**
     * 通过仓储员id、对于部门（新/老食堂）、状态 查询待处理的数量
     * @param clerkId
     * @param canteenId
     * @param status
     * @return
     */
    @Override
    public SmallCanteenPurchaseDTO getTotal(Long chedId, Long clerkId, Long canteenId, int status) {
        String clerk_Id="";
        String canteen_Id="";
        String ched_Id="";
        if(null != chedId){
            ched_Id = " and  ched_id = "+chedId;
        }
        if(null != clerkId){
            clerk_Id = " and  canteen_admin_id = "+clerkId;
        }
        if(null != canteenId){
            canteen_Id = " and  canteen_id = "+canteenId;
        }
        SmallCanteenPurchaseDTO total = smallCanteenPurchaseDao.getTotal(ched_Id,clerk_Id, canteen_Id, status);
        return total;
    }
}